package com.ekuaitu.kuaitu.utils;

import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.multidex.MultiDex;

import com.autonavi.amap.mapcore.Md5Utility;
import com.ekuaitu.kuaitu.activity.MainActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Build.VERSION.SDK;


/**
 * Created by Michael Pi on 2016/10/9.
 */
public class MyApplication extends Application {
    {
        PlatformConfig.setWeixin("wx043e0f0a1710f0c0", "dc6ee838c6f72b72035e8897e233180f");
        PlatformConfig.setQQZone("1105741120", "PJ8L5RKO1Gg7wFb1");
        Config.DEBUG = true;
    }

    private static MyApplication instance;
    public static byte[] btToken;
    public static int power;
    private static String uid;
    private static String token;
    private String imageUrl;
    private String hotLine;
    private static String appVersion;
    private VerControlUtils verControl;
    public static OnRemindCarListener onRemindCar;
    private static String sign;
    private static String orderId;
    private static String areaCode;
    private static String adCode;

    public static MyApplication getInstance() {
        return instance;
    }

    private Context mContext = this;

    @Override
    public void onCreate() {
        super.onCreate();
        UMShareAPI.get(this);
        instance = this;
        initUmeng();
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        MobclickAgent.openActivityDurationTrack(false);
        verControl = new VerControlUtils(this);
        appVersion = verControl.getVersionName();
    }

    private void initUmeng() {
        //接收友盟消息
        final PushAgent mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(true);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.DEVICE_TOKEN, deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });


        //接收友盟通知，无需点击通知，即可接收自定义参数
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public Notification getNotification(final Context context, final UMessage msg) {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        if (onRemindCar != null) {
                            onRemindCar.remindCar();
                        }
                    }
                });
                return super.getNotification(context, msg);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        //接收友盟通知，需点击通知，即可接收自定义参数
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void launchApp(Context context, UMessage uMessage) {
                super.launchApp(context, uMessage);
                remindCar(uMessage);
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
                remindCar(uMessage);
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
    }

    private void remindCar(UMessage msg) {
        Map<String, String> notifyMap = new HashMap<>();
        for (Map.Entry<String, String> entry : msg.extra.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            notifyMap.put(key, value);
        }
        if (notifyMap.get("type").equals("remindCar")) {
            //以下页面在前台，点击有车提醒通知不跳转
            if (isForeground(mContext)) {

            } else {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("notifyMap", (Serializable) notifyMap);
                intent.putExtra("remindCar", true);
                intent.setClass(mContext, MainActivity.class);
                startActivity(intent);
            }
        }
    }


    //判断页面是否在前台,在前台不跳转
    private boolean isForeground(Context context) {
        if (context == null) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.AdPopActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.SettlementActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.CarSettlementDetailActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.CarInUseActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.BikeInUseActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.BikeInUseRedActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.BikeSettlementDetailActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.BikeRedTaskActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.LoginActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.SplashActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.GuideActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.ChooseCouponActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.CarCertificateActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.RepairBTBikeActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.BikeCertificateActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.NaviActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.activity.FestivalActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.wxapi.WXEntryActivity") ||
                    cpn.getClassName().equals("com.ekuaitu.kuaitu.wxapi.WXPayEntryActivity") ||
                    cpn.getClassName().equals("com.umeng.qq.tencent.AuthActivity") ||
                    cpn.getClassName().equals("com.umeng.qq.tencent.AssistActivity")
                    ) {
                return true;
            }
        }
        return false;
    }


    public interface OnRemindCarListener {
        void remindCar();
    }

    public static void setOnRemindCarListener(OnRemindCarListener onRemindCarListener) {
        onRemindCar = onRemindCarListener;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    //uid
    public String getUid() {
        if (uid == null || uid.equals("")) {
            uid = SharedPreferencesUtils.getInstance(getApplicationContext()).getStringValue(SharedPreferencesKey.USER_ID);
        }
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue(SharedPreferencesKey.USER_ID, uid);
    }

    //token
    public String getToken() {
        if (token == null || token.equals("")) {
            token = SharedPreferencesUtils.getInstance(getApplicationContext()).getStringValue(SharedPreferencesKey.USER_TOKEN);
        }
        return token;
    }

    public void setToken(String token) {
        this.token = token;
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue(SharedPreferencesKey.USER_TOKEN, token);
    }


    //appVersion
    public String getAppVersion() {
        if (appVersion == null || appVersion.equals("")) {
            verControl = new VerControlUtils(this);
            appVersion = verControl.getVersionName();
        }
        return appVersion;
    }

    //sdkVersion
    public String getSdkVersion() {
        return SDK;
    }

    //imageUrl
    public String getImageUrl() {
        if (imageUrl == null || imageUrl.equals("")) {
            imageUrl = SharedPreferencesUtils.getInstance(getApplicationContext()).getStringValue("imageUrl");
        }
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue("imageUrl", imageUrl);
    }

    //hotLine
    public String getHotLine() {
        if (hotLine == null || hotLine.equals("")) {
            hotLine = SharedPreferencesUtils.getInstance(getApplicationContext()).getStringValue("hotLine");
        }
        return hotLine;
    }

    public void setHotLine(String hotLine) {
        this.hotLine = hotLine;
        SharedPreferencesUtils.getInstance(getApplicationContext()).putStringValue("hotLine", hotLine);
    }


    //sign&timestamp
    public String getTimestamp() {
        String timestamp = new Date().getTime() + "";
        sign = Md5Utility.getStringMD5(timestamp + "ekuaitu1"); //时间戳+ekuaitu+1(平台)
        return timestamp;
    }

    public String getSign() {
        return sign;
    }


    public String getAreaCode() {
        return areaCode;
    }

    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }

    public String getAdCode() {
        return adCode;
    }

    public void setAdCode(String adCode) {
        this.adCode = adCode;
    }


    private Map<String, String> requestFieldMap;

    public Map<String, String> getRequestFieldMap() {
        if (requestFieldMap == null) {
            requestFieldMap = new HashMap<>();
        }
        String uid = getUid();
        if (uid != null) {
            requestFieldMap.put("userId", uid);
            requestFieldMap.put("uid", uid);
            requestFieldMap.put("token", getToken());
        } else {
            requestFieldMap.remove("userId");
            requestFieldMap.remove("uid");
            requestFieldMap.remove("token");
        }
        requestFieldMap.put("appVersion", getAppVersion());
        requestFieldMap.put("phoneSysVersion", getSdkVersion());
        requestFieldMap.put("plateForm", "1");
        requestFieldMap.put("platform", "1");
        if (getAreaCode() != null) {
            requestFieldMap.put("areaCode", getAreaCode());
        }
        if (getAdCode() != null) {
            requestFieldMap.put("adCode", getAreaCode());
        }
        requestFieldMap.put("timestamp", getTimestamp());
        requestFieldMap.put("sign", getSign());
        return requestFieldMap;
    }

}
